const express = require('express')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const favicon = require('serve-favicon')
const ejs = require('ejs')
const path = require('path')
// const history = require('connect-history-api-fallback')
const common = require('./middlewares/common.middleware')
const config = require('./config')
const routes = require('./routes')

const app = express()

app.$config = config.get()

// view engine setup
app.set('views', path.join(__dirname, '../views'))
app.engine('.html', ejs.__express)
app.set('view engine', 'html')
app.use(favicon(path.join(__dirname, '../public', 'favicon.ico')))

app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(session({
  // 生产环境请无使用 FileStore，会存在一些bug
  store: new FileStore({
    path: path.resolve(__dirname, '../.sessions')
  }),
  secret: 'bdc65fd59c8b4998361dc455af536082',
  name: 'ZY-SERVER',
  cookie: { maxAge: 30 * 24 * 3600 * 1000 },
  resave: false,
  saveUninitialized: false
}))

app.use(common)
// app.use('/dist', history(), express.static(path.resolve(__dirname, '../dist')))

// router
for (const i in routes) {
  app.use(routes[i].perfix, routes[i].router)
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = err
  res.locals.url = req.url

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

module.exports = app
